﻿using AngleSharp.Dom;
using System.Text;

namespace CodeGenerator {
    /// <summary>
    /// 
    /// </summary>
    public class ClientCodeFactory {
        #region 全局变量
        static string DalNameSpace = "MapleLeaf.Application.CookBook";//DAL层命名空间（下同）
        #endregion
        public static string Create(string clientName, Dictionary<string, string> pairs, string? group = null, string? nsStr = null) {
            StringBuilder sb = new();
            if (group != null && nsStr != null) {
                sb.AppendLine($"using MapleLeaf.Model.CookBook.{group}.{nsStr}.Entity;");
                sb.AppendLine($"using MapleLeaf.Service.CookBook.{group}.{nsStr};");
            } else if (group != null) {
                sb.AppendLine($"using MapleLeaf.Model.CookBook.{group}.Entity;");
                sb.AppendLine($"using MapleLeaf.Service.CookBook.{group};");
            } else if (nsStr != null) {
                sb.AppendLine($"using MapleLeaf.Model.CookBook.{nsStr}.Entity;");
                sb.AppendLine($"using MapleLeaf.Service.CookBook.{nsStr};");
            }else {
                sb.AppendLine($"using MapleLeaf.Model.CookBook.Entity;");
                sb.AppendLine($"using MapleLeaf.Service.CookBook;");
            }
            sb.AppendLine("");
            sb.AppendLine($"namespace {DalNameSpace}.{group} {{");
            sb.AppendLine($"public class {clientName}Client:IApplicationClient {{");

            foreach (var item in pairs) {
                sb.AppendLine($"private readonly {item.Key.Replace("Entity", "Service")} _{item.Key.Replace("Entity", "").ToLowerCamelCase()};");
            }
            sb.AppendLine("/// <summary>");
            sb.AppendLine($"/// 构造函数");
            sb.AppendLine("/// </summary>");
            sb.Append($"public {clientName}Client(");
            int index = 0;
            foreach (var item in pairs) {
                if (index == pairs.Count - 1) {
                    sb.Append($"{item.Key.Replace("Entity", "Service")} {item.Key.Replace("Entity", "").ToLowerCamelCase()}){{");
                } else {
                    sb.Append($"{item.Key.Replace("Entity", "Service")} {item.Key.Replace("Entity", "").ToLowerCamelCase()},");
                }
                index++;
            }
            foreach (var item in pairs) {
                sb.AppendLine($"_{item.Key.Replace("Entity", "").ToLowerCamelCase()} = {item.Key.Replace("Entity", "").ToLowerCamelCase()};");
            }
            sb.AppendLine($"}}");
            foreach (var item in pairs) {
                sb.AppendLine($"#region {item.Value}");
                CratePageListMethod(sb, item.Key, item.Value);
                CrateListMethod(sb, item.Key, item.Value);
                CrateGetInfoMethod(sb, item.Key, item.Value);
                CrateSaveMethod(sb, item.Key, item.Value);
                CrateDeleteMethod(sb, item.Key, item.Value);
                sb.AppendLine("#endregion");
            }
            sb.AppendLine("}");
            sb.AppendLine("}");

            var file = CreateTxt($"{clientName}Client.cs", sb.ToString());
            return file;
        }

        private static void CratePageListMethod(StringBuilder sb, string typeName, string desc) {
            sb.AppendLine("/// <summary>");
            sb.AppendLine($"/// 获取{desc}列表");
            sb.AppendLine("/// </summary>");
            sb.AppendLine("/// <returns></returns>");
            sb.AppendLine($"public async Task<PaginationModel<{typeName}>> Get{typeName.Replace("Entity", "")}PageListAsync(Expression<Func<{typeName}, bool>> whereExp, PaginationModel pagination) {{");
            sb.AppendLine($"var page = pagination.Adapt<PaginationModel<{typeName}>>();");
            sb.AppendLine("RefAsync<int> total = 0;");
            sb.AppendLine($"var res = await _{(typeName.Replace("Entity", "")).ToLowerCamelCase()}.GetPageListAsync(whereExp,page.PageIndex, page.PageSize, total);");
            sb.AppendLine("page.Total = total;");
            sb.AppendLine("page.Record = res;");
            sb.AppendLine("return page;");
            sb.AppendLine("}");
        }

        private static void CrateListMethod(StringBuilder sb, string typeName, string desc) {
            sb.AppendLine("/// <summary>");
            sb.AppendLine($"/// 获取{desc}列表");
            sb.AppendLine("/// </summary>");
            sb.AppendLine("/// <returns></returns>");
            sb.AppendLine($"public async Task<List<{typeName}>> Get{typeName.Replace("Entity", "")}ListAsync(Expression<Func<{typeName}, bool>> whereExp) {{");
            sb.AppendLine($"var res = await _{(typeName.Replace("Entity", "")).ToLowerCamelCase()}.GetListAsync(whereExp);");
            sb.AppendLine("return res;");
            sb.AppendLine("}");
        }
        private static void CrateGetInfoMethod(StringBuilder sb, string typeName, string desc) {
            sb.AppendLine("/// <summary>");
            sb.AppendLine($"/// 获取{desc}信息");
            sb.AppendLine("/// </summary>");
            sb.AppendLine("/// <returns></returns>");
            sb.AppendLine($"public async Task<{typeName}> Get{typeName.Replace("Entity", "")}InfoAsync(long id) {{");
            sb.AppendLine($"var res = await _{(typeName.Replace("Entity", "")).ToLowerCamelCase()}.GetByIdAsync(id);");
            sb.AppendLine("return res;");
            sb.AppendLine("}");
        }
        private static void CrateSaveMethod(StringBuilder sb, string typeName, string desc) {
            sb.AppendLine("/// <summary>");
            sb.AppendLine($"/// 保存{desc}信息");
            sb.AppendLine("/// </summary>");
            sb.AppendLine("/// <returns></returns>");
            sb.AppendLine($"public async Task<long> Save{typeName.Replace("Entity", "")}Async({typeName} entity) {{");
            sb.AppendLine(" long id;");
            sb.AppendLine("if (entity.Id == 0) {");
            sb.AppendLine($" var res = await _{(typeName.Replace("Entity", "")).ToLowerCamelCase()}.InsertReturnEntityAsync(entity);");
            sb.AppendLine(" id = res != null ? res.Id : 0;");
            sb.AppendLine("}");
            sb.AppendLine("else{");
            sb.AppendLine($" var res = await _{(typeName.Replace("Entity", "")).ToLowerCamelCase()}.UpdateAsync(entity);");
            sb.AppendLine(" id = res >0 ? entity.Id : 0;");
            sb.AppendLine("}");
            sb.AppendLine("return id;");
            sb.AppendLine("}");
        }
        private static void CrateDeleteMethod(StringBuilder sb, string typeName, string desc) {
            sb.AppendLine("/// <summary>");
            sb.AppendLine($"/// 删除{desc}信息");
            sb.AppendLine("/// </summary>");
            sb.AppendLine("/// <returns></returns>");
            sb.AppendLine($"public async Task<bool> Delete{typeName.Replace("Entity", "")}Async(List<long> ids) {{");
            sb.AppendLine($"var res = await _{(typeName.Replace("Entity", "")).ToLowerCamelCase()}.DeleteByIdAsync(ids);");
            sb.AppendLine("return res > 0;");
            sb.AppendLine("}");
        }



        private static string CreateTxt(string fileName, string str) {
            var filePath = Path.Combine("D:\\新建文件夹", fileName);
            StreamWriter sw = File.CreateText(filePath);
            sw.Write(str);  //写入文件中
            sw.Flush();//清理缓冲区
            sw.Close();//关闭文件
            return filePath;
        }
    }
    public static class ExHandler {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToLowerCamelCase(this string str) {
            if (string.IsNullOrEmpty(str)) {
                return str;
            }
            // 将第一个字符转换为小写
            string firstChar = str.Substring(0, 1).ToLower();
            // 获取剩余字符
            string restOfString = str.Substring(1);
            // 将剩余字符与首字母拼接起来
            string camelCase = firstChar + restOfString;
            return camelCase;
        }
    }

}
